﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DinhMuc.BUL;
using DinhMuc.Public;
using System.Data.OleDb;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using Janus.Windows.GridEX;

namespace DinhMuc.UI.Form_bang
{
    public partial class frm_sanPham : UserControl
    {
        public frm_sanPham()
        {
            InitializeComponent();
        }
        tblSanPhamBUL sp = new tblSanPhamBUL();
        private void frm_sanPham_Load(object sender, EventArgs e)
        {
            //tblPhanQuyenBUL p = new tblPhanQuyenBUL();
           // int exe = p.xetPhanQuyenTrongForm(Form1.maQuanLy, this.Name, btnXem, btnThem, btnXoa, btnSua);
            gridEX1.DataSource = sp.bangSP();
        }

        private void gridEX1_RecordAdded(object sender, EventArgs e)
        {
            string maSP = gridEX1.GetValue("maSP").ToString();
            string tenSP = gridEX1.GetValue("tenSP").ToString();
            string cauTruc = gridEX1.GetValue("cauTruc").ToString();
            string quyCach = gridEX1.GetValue("quyCach").ToString();
            int slTonKho = int.Parse("0"+gridEX1.GetValue("slTonKho").ToString());
            int slSanXuat = int.Parse("0"+gridEX1.GetValue("slSanXuat").ToString());
            string slPhanTram = gridEX1.GetValue("slPhanTram").ToString();
            string trucInPKDBB = gridEX1.GetValue("trucInPKDBB").ToString();
            string nlMang_pvt = gridEX1.GetValue("nlMang_pvt").ToString();
            string nlHat_phuGia = gridEX1.GetValue("nlHat_phuGia").ToString();
            tblSanPhamPublic p = new tblSanPhamPublic(
                maSP, tenSP, cauTruc, quyCach, slTonKho, slSanXuat, slPhanTram, trucInPKDBB, nlMang_pvt, nlHat_phuGia
                );
            sp.ThemSP(p);
            frm_sanPham_Load(sender, e);
        }

        private void gridEX1_RecordUpdated(object sender, EventArgs e)
        {
            string maSP = gridEX1.GetValue("maSP").ToString();
            string tenSP = gridEX1.GetValue("tenSP").ToString();
            string cauTruc = gridEX1.GetValue("cauTruc").ToString();
            string quyCach = gridEX1.GetValue("quyCach").ToString();
            int slTonKho = int.Parse("0" + gridEX1.GetValue("slTonKho").ToString());
            int slSanXuat = int.Parse("0" + gridEX1.GetValue("slSanXuat").ToString());
            string slPhanTram = gridEX1.GetValue("slPhanTram").ToString();
            string trucInPKDBB = gridEX1.GetValue("trucInPKDBB").ToString();
            string nlMang_pvt = gridEX1.GetValue("nlMang_pvt").ToString();
            string nlHat_phuGia = gridEX1.GetValue("nlHat_phuGia").ToString();
            tblSanPhamPublic p = new tblSanPhamPublic(
                maSP, tenSP, cauTruc, quyCach, slTonKho, slSanXuat, slPhanTram, trucInPKDBB, nlMang_pvt, nlHat_phuGia
                );
            sp.suaSP(p);
            frm_sanPham_Load(sender, e);
        }

        string maSP = "";
        private void gridEX1_DeletingRecord(object sender, Janus.Windows.GridEX.RowActionCancelEventArgs e)
        {
            maSP = gridEX1.GetValue("maSP").ToString();
        }

        private void gridEX1_RecordsDeleted(object sender, EventArgs e)
        {
            DialogResult dlr = MessageBox.Show("Bạn có chắc muốn xóa không?", "WARNNING",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dlr == DialogResult.OK)
            {
                sp.xoaSP(maSP);
                frm_sanPham_Load(sender, e);
            }
        }

        private void imPort_Click(object sender, EventArgs e)
        {
            
            OpenFileDialog file = new OpenFileDialog();
            if (file.ShowDialog() == DialogResult.OK)
            {
                OleDbConnection connect = new OleDbConnection();
                connect.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file.FileName + ";Extended Properties=Excel 4.0";
                if (connect.State == ConnectionState.Closed)
                    connect.Open();
                OleDbCommand command = new OleDbCommand("select * from [sheet1$]", connect);
                OleDbDataAdapter adapter = new OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow row = dt.Rows[i];
                    tblSanPhamPublic p = new tblSanPhamPublic();
                    p.MaSP= row[0].ToString();
                    p.TenSP= row[1].ToString();
                    p.CauTruc= row[2].ToString();
                    p.QuyCach= row[3].ToString();
                    p.SlTonKho= int.Parse("0"+row[4].ToString());
                    p.SlSanxuat= int.Parse("0"+row[5].ToString());
                    p.SlPhanTram= row[6].ToString();
                    p.TrucInPKDBB= row[7].ToString();
                    p.NvMang_pvt= row[8].ToString();
                    p.NlHat_phuGia = row[9].ToString();

                    sp.import("insert into SanPham(maSP,tenSP,cauTruc,quyCach,slTonKho,slSanXuat,slPhanTram,trucInPKDBB,nlMang_pvt,nlHat_phuGia)values(@A,@B,@C,@D,@E,@F,@G,@H,@I,@J)", p);

                }
                MessageBox.Show("Import Dữ Liệu Thành Công");
            }
        }
        //In
        private void button3_Click(object sender, EventArgs e)
        {
            GridEXPrintDocument print = new GridEXPrintDocument();
            PrintPreviewDialog PrintPreviewDialog1 = new PrintPreviewDialog();

            PrintPreviewDialog1.Document = print;
            print.DefaultPageSettings.Landscape = true;
            print.GridEX = this.gridEX1;
            print.ExpandFarColumn = true;
            PrintPreviewDialog1.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
            PrintPreviewDialog1.ShowDialog();
        }
        //excel
        private void btnExcel_Click(object sender, EventArgs e)
        {
            this.saveFileDialog1.Filter = "txt files (*.xls)|*.xls|All files (*.*)|*.*";
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = this.saveFileDialog1.FileName;
                FileStream stream = new FileStream(fileName.Trim(), FileMode.Create);
                this.gridEXExporter1.Export(stream);
                stream.Close();
                MessageBox.Show("Xuất thành công!");
            }
        }
        //PDF
        private void button4_Click(object sender, EventArgs e)
        {
            this.saveFileDialog1.Filter = "txt files (*.pdf)|*.fdf|All files (*.*)|*.*";
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = this.saveFileDialog1.FileName;
                ExportToPdf(sp.bangSP(), saveFileDialog1.FileName);
                MessageBox.Show("Xuất thành công!");
            }
        }
        //word
        private void button2_Click(object sender, EventArgs e)
        {
            this.saveFileDialog1.Filter = "txt files (*.doc)|*.docx|All files (*.*)|*.*";
            if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = this.saveFileDialog1.FileName;
                Export2Word(sp.bangSP());
                MessageBox.Show("Xuất thành công!");
            }
        }
        void Export2Word(DataTable datatable1)
        {
            //Tạo các đối tượng application, document, table của MS Word
            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc;
            Microsoft.Office.Interop.Word.Table table;

            //Hiện (mở) ứng dụng word
            app.Visible = true;

            //Tham số truyền vào các hàm có đối là tuỳ chọn
            object obj = Type.Missing;

            //Tạo một tài liệu mới (để chứa dữ liệu xuất ra)
            doc = app.Documents.Add(ref obj, ref obj, ref obj, ref obj);

            Microsoft.Office.Interop.Word.Range range = doc.Range(ref obj, ref obj);

            //Thêm một bảng có 2 cột và số hàng bằng với số hàng trong datatable.
            table = doc.Tables.Add(range, datatable1.Rows.Count, datatable1.Columns.Count, ref obj, ref obj);

            //Xuất dữ liệu từ datatable sang bảng (trong word). Chú ý: đối với các đối tượng tập hợp
            // trong word thì phần tử đầu tiên có chỉ số là 1 thay vì 0 như trong C#
            for (int i = 0; i < datatable1.Rows.Count; i++)
            {
                for (int j = 0; j < datatable1.Columns.Count; j++)
                {
                    doc.Tables[1].Rows[i + 1].Cells[j + 1].Range.Text = datatable1.Rows[i][j].ToString();
                }
                //doc.Tables[1].Rows[i + 1].Cells[1].Range.Text = datatable1.Rows[i]["STT"].ToString();
                //doc.Tables[1].Rows[i + 1].Cells[2].Range.Text = datatable1.Rows[i]["HoTen"].ToString();
            }
            //Thêm đường viền cho Table nếu cần.
            doc.Select();
            Microsoft.Office.Interop.Word.WdLineStyle BorderValue = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineStyle = BorderValue;
            app.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineStyle = BorderValue;
        }
        public void ExportToPdf(DataTable dt, string path)
        {
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
            document.Open();
            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

            PdfPTable table = new PdfPTable(dt.Columns.Count);
            PdfPRow row = null;
            //float[] widths = new float[4];
            //widths[0] = 4F;
            //widths[1] = 4F;
            //widths[2] = 4F;
            //widths[3] = 4F; 

            //table.SetWidths(widths);

            table.WidthPercentage = 100;
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("Products"));

            cell.Colspan = dt.Columns.Count;

            foreach (DataColumn c in dt.Columns)
            {

                table.AddCell(new Phrase(c.ColumnName, font5));
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        table.AddCell(new Phrase(r[i].ToString(), font5));
                    }
                    //table.AddCell(new Phrase(r[2].ToString(), font5));
                    //table.AddCell(new Phrase(r[3].ToString(), font5));
                }
            } document.Add(table);
            document.Close();
        }

       
    }
}
